import uvicorn
from fastapi import FastAPI
from pydantic import BaseModel
import requests
import json

app = FastAPI()

block_lis = ["yuebai","yuebuy","my22","miyuan","蜜源","悦拜","lg22"]

class GroupInfoRequestMiyue(BaseModel):
    groupId: str

"""
######################################### 蜜月 #########################################
"""

# 获取分类信息
# def get_category_miyu():
#     url = 'https://api.yuebai.biz/api/material/groupLabels'
#     response = requests.post(url)
#     result = json.loads(response.content.decode())
#     return result

# 获取分类下的群信息
def get_groups_miyu():
    url = 'https://api.gzmiyuan.com/api/wechat/user/openApi/getAllSourceGroupList'
    response = requests.get(url)
    group_result = response.json()
    return group_result

# 获取指定群信息
def get_group_info_miyu(groupId):
    info_list = []

    url = f'https://api.gzmiyuan.com/api/wechat/message/openApi/listSourceGroupMsgByPage?groupId={groupId}&materialId=&wechatId=&page=1&rows=10'

    try:
        response = requests.get(url,  timeout=3)
        group_info_result = response.json()

        ####
        temp = []
        for _, i in enumerate(group_info_result['data']):
            for kw in block_lis:
                if kw in i['msgContent']:
                    temp.append(_)
                    break
        temp.sort()
        for i in temp[::-1]:
            del group_info_result['data'][i]
        ####

        info_list.append(group_info_result)
        if not group_info_result.get('data'):
            return info_list
    except Exception as e:
        print(f"Request failed: {e}")
    return info_list

# # API 路由：获取分类
# @app.get("/get_category_miyu")
# async def get_category_endpoint():
#     category_result = get_category()
#     return category_result

# API 路由：根据分类获取群信息
@app.get("/get_groups_miyu")
async def get_groups_endpoint():
    """
    {
        "sort": "your_sort_value"
    }
    """
    group_result = get_groups_miyu()
    return group_result

# API 路由：获取群信息
@app.post("/get_group_info_miyu")
async def get_group_info_endpoint(request: GroupInfoRequestMiyue):
    """
    {
        "groupId": "groupId"
    }
    """
    group_info_result = get_group_info_miyu(request.groupId)
    return group_info_result


"""
######################################### 月拜 #########################################
"""
# 定义请求体数据模型
class SortRequest(BaseModel):
    sort: int

class GroupInfoRequest(BaseModel):
    reception_id: int
    type:int


# 获取分类信息
def get_category():
    url = 'https://api.yuebai.biz/api/material/groupLabels'
    response = requests.post(url)
    result = json.loads(response.content.decode())
    return result

# 获取分类下的群信息
def get_groups(sort):
    
    ####  老接口  使用这个接口获得的群id去进一步获取群信息时 无数据返回
    
    # url = 'https://api.yuebai.biz/api/material/groupList'
    # data = {'sort': sort}
    
    ####
    
    url = 'https://api.yuebai.biz/api/wechat/groupList'
    
    data = {
        'type': sort,
    }

    response = requests.post(url, data=data)
    group_result = response.json()
    return group_result

# 获取指定群信息
def get_group_info(reception_id,tp):
    info_list = []
    url = 'https://api.yuebai.biz/api/wechat/groupMsgList'
    data = {
        'reception_id': reception_id,
        'page_size': '10',
        'scrollId': '1',
        'page': '1',
        'type': tp,
        'keyword': '',
    }
    headers = {
        'Host': 'api.yuebai.biz',
        'Content-Type': 'application/x-www-form-urlencoded'
    }
    try:
        response = requests.post(url, data=data, timeout=3,headers=headers)

        group_info_result = response.json()

        ####
        temp = []
        for _, i in enumerate(group_info_result['data']['list']):
            for kw in block_lis:
                if kw in i['msgContent']:
                    temp.append(_)
                    break

        temp.sort()
        for i in temp[::-1]:
            del group_info_result['data']['list'][i]
        ####

        info_list.append(group_info_result)
        if not group_info_result.get('data'):
            return info_list
    except Exception as e:
        print(f"Request failed: {e}")
    return info_list

# API 路由：获取分类
@app.get("/get_category")
async def get_category_endpoint():
    category_result = get_category()
    return category_result

# API 路由：根据分类获取群信息
@app.post("/get_groups")
async def get_groups_endpoint(request: SortRequest):
    """
    {
        "sort": "your_sort_value"
    }
    """
    group_result = get_groups(request.sort)
    return group_result

# API 路由：获取群信息
@app.post("/get_group_info")
async def get_group_info_endpoint(request: GroupInfoRequest):
    """
    {
        "reception_id": "your_reception_id"
    }
    """
    group_info_result = get_group_info(request.reception_id, request.type)
    return group_info_result

if __name__ == '__main__':
    uvicorn.run(app='main:app', host="127.0.0.1", port=5000, reload=True)
